<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class User_Model extends MY_Model {
    public function __construct() {
        parent::__construct();
        $this->load->model('entity/user_entity', 'User_Entity');
    }

    public function checkUserExist($option, $id = null) {
        $this->db->select('a.id', true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->where('a.username', $option['username']);
        if ($id != null) {
            $this->db->where('a.id <>', $id);
        }
        if ($this->db->count_all_results()) {
            return UPDATE_USER_DUPLICATE_USERNAME;
        }

        $this->db->select('a.id', true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->where('a.email', $option['email']);
        if ($id != null) {
            $this->db->where('a.id <>', $id);
        }
        if ($this->db->count_all_results() > 0) {
            return UPDATE_USER_DUPLICATE_EMAIL;
        }

        return 0;
    }

    public function login($data) {
        $select = 'a.id, a.deleted_at, a.active_flg, a.password, a.image_folder, a.image, a.role, a.full_name';
        $user = $this->getUserByUsername($data['username'], $select);
        if ($user == null || $user->getDeletedAt() != null || $user->getActiveFlg() != 1) {
            return null;
        }
        $plaintext_string = $this->encrypt->decode($user->getPassword());
        if ($data['password'] != $plaintext_string) {
            return null;
        }
        $date = get_current_date();
        $this->db->trans_begin();
        $this->db->where('id', $user->getId());
        $this->db->update($this->table_user_name, array('last_login' => $date));
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return null;
        } else {
            $this->db->trans_commit();
        }
        return $user;
    }

    public function logout($id) {
        $date = new DateTime('now');
        $date = $date->format(DATE_TIME_FORMAT);
        $this->db->trans_begin();
        $this->db->where('id', $id);
        $this->db->update($this->table_user_name, array('last_logout' => $date));
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }

    public function getUserById($id, $isGetShop = false, $sSelect=NULL) {
        $select = '';
        if($sSelect!=NULL){
            $select = $sSelect;
        } else {
            $select = 'a.id, a.role, a.username, a.password, a.email, a.phone,
            a.home_phone,a.skype,a.gmap,
            a.address, a.full_name, a.gender, a.birthday, a.last_login, a.active_flg, a.created_at,
            a.deleted_at';
        }
        if ($isGetShop) {
            $select .= ", b.id as shop_id, b.title as shop_title, b.slug as shop_slug";
        }
        $this->db->select($select, true);
        $this->db->from($this->table_user_name . ' AS a');
        if ($isGetShop) {
            $this->db->join($this->table_shop_name . ' b', 'b.user_id=a.id');
        }
        $this->db->where('a.id', $id);
        $result = $this->db->get()->first_row('User_Entity');
        return $result;
    }

    public function getUserByUsername($username, $sSelect=NULL) {
        $select = '';
        if($sSelect!=NULL){
            $select = $sSelect;
        } else {
            $select = 'a.id, a.role, a.username, a.password, a.email, a.phone,
            a.address, a.full_name, a.birthday, a.last_login, a.active_flg, a.created_at,
            a.deleted_at';
        }
        $result = null;
        $this->db->select($select, true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->where('a.username', $username);
        $result = $this->db->get()->first_row('User_Entity');
        return $result;
    }

    public function getUserByEmail($email) {
        $result = null;
        $this->db->select('a.id, a.role, a.username, a.password, a.email, a.phone,
            a.address, a.full_name, a.birthday, a.last_login, a.active_flg, a.created_at,
            a.deleted_at', true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->where('a.email', $email);
        $result = $this->db->get()->first_row('User_Entity');
        return $result;
    }

    public function getUserByShopSlug($slug, $select=null) {
        $result = null;
        if($select==null) {
            $select = 'a.id, a.email, a.phone, a.address, a.full_name, a.birthday, a.skype,  a.last_login, a.active_flg, a.created_at, b.title as shop_title';
        }
        $this->db->select($select, true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->join($this->table_shop_name . ' b', 'a.id=b.user_id');
        $this->db->where('b.slug', $slug);
        $result = $this->db->get()->first_row('User_Entity');
        return $result;
    }

    /////////////////////////////// BEGIN SIGNUP ACTIVE AREA /////////////////////////////
    public function getUserByActiveLink($code) {
        $result = null;
        $this->db->select('a.id, a.username, a.full_name, a.email, a.active_code', true);
        $this->db->from($this->table_user_temp_name . ' AS a');
        $this->db->where('a.active_code', $code);
        $this->db->where('a.opt_case', CASE_REGISTER);
        $this->db->where('a.deleted_at', null);
        $result = $this->db->get()->first_row('User_Entity');
        return $result;
    }

    public function getUserTempById($id) {
        $result = null;
        $this->db->select('a.id, a.username, a.password, a.email, a.full_name, a.created_at', true);
        $this->db->from($this->table_user_temp_name . ' AS a');
        $this->db->where('a.id', $id);
        $this->db->where('a.deleted_at', null);
        $result = $this->db->get()->first_row('User_Entity');
        return $result;
    }

    public function signup($data) {
        $this->db->select('a.id', true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->where('a.username', $data['username']);
        $this->db->or_where('a.email', $data['email']);
        $result = $this->db->count_all_results();
        if ($result > 0) {
            return false;
        }
        $this->db->select('a.id', true);
        $this->db->from($this->table_user_temp_name . ' AS a');
        $this->db->where('a.username', $data['username']);
        $this->db->or_where('a.email', $data['email']);
        $result = $this->db->count_all_results();
        if ($result > 0) {
            return false;
        }

        $this->db->trans_begin();
        $this->db->insert($this->table_user_temp_name, $data);
        //send mail
        $aInfo = array(
            'subject' => SITE_NAME . ' - Xác nhận đăng kí tài khoản',
            'template' => 'mail-template/signup.html.php',
            'data' => array(
                'full_name' => $data['full_name'],
                'username' => $data['username'],
                'active_code' => $data['active_code']
                ),
            'email' => $data['email'],
            'address' => array()
            );
        $this->load->library('event');
        $resultMailer = $this->event->sendMail($aInfo);
        if ($this->db->trans_status() === false || !$resultMailer) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
            return true;
        }
        return false;
    }

    public function active($user, $temp_user_id) {
        $user->image_folder = random_string('alnum', 18);;
        $user = get_object_vars($user);
        unset($user['id']);
        unset($user['active_code']);
        unset($user['last_login']);
        unset($user['last_logout']);
        unset($user['deleted_at']);

        $this->db->trans_begin();
        $this->db->insert($this->table_user_name, $user);

        //delete logic temp user
        $this->db->where('id', $temp_user_id);
        $this->db->update($this->table_user_temp_name, array('deleted_at' => $user['updated_at']));

        //make dir all folder need shop image folder
        $cmdMkDir = makeShopImageFolderDir($user['image_folder'], unserialize(PERSONAL_FOLDER));

        if (!$cmdMkDir || $this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }
    ////////////////////////////////// END SIGNUP ACTIVE //////////////////////////////////////

    ////////////////////////////////// FORGET PASSWORD //////////////////////////////////////
    /**
    * @Search for db emails and create a server request if exist, return link code
    * @table user_temp
    * @param  $email
    * @return boolean
    */
    public function createForgetPasswordRequest($email, $code) {
        $result = 0;
        $this->db->select('a.id, a.full_name', true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->where('a.email', $email);
        $this->db->where('a.role <>', ROLE_ADMIN);
        $this->db->where('a.active_flg', 1);
        $this->db->where('a.deleted_at', null);
        $result = $result = $this->db->get()->result('User_Entity');;
        if(count($result)>0){
            $data = array(
                'username'    => $this->encrypt->encode(rand().get_current_date()),
                'opt_case'    => CASE_FORGET_PASSWORD,
                'opt_more'    => $result[0]->id,
                'email'       => $email,
                'active_code' => $code,
                'created_at'  => get_current_date()
                );
            $this->db->trans_begin();
            $this->db->insert($this->table_user_temp_name, $data);
            if ($this->db->trans_status() === false && $this->db->affected_rows() > 0) {
                $this->db->trans_rollback();
            } else {
                //send mail
                $aInfo = array(
                    'subject' => SITE_NAME . ' - Thay đổi thông tin đăng nhập',
                    'template' => 'mail-template/forget-password.html.php',
                    'data' => array(
                        'full_name' => $result[0]->full_name,
                        'active_code' => $code
                        ),
                    'email' => $email,
                    'address' => array()
                    );
                $this->load->library('event');
                $resultMailer = $this->event->sendMail($aInfo);
                if(!$resultMailer){
                    $this->db->trans_rollback();
                } else {
                    $this->db->trans_commit();
                    return true;
                }
            }
        }
        return false;
    }

    public function getForgetPasswordUserByActiveLink($code) {
        $result = null;
        $this->db->select('a.id, a.opt_more', true);
        $this->db->from($this->table_user_temp_name . ' AS a');
        $this->db->where('a.active_code', $code);
        $this->db->where('a.opt_case', CASE_FORGET_PASSWORD);
        $this->db->where('a.deleted_at', null);
        $result = $this->db->get()->first_row();
        return $result;
    }

    public function updateForgetPasswordUserByActiveLink($temp_id, $id, $new_password) {
        $result = 0;
        $this->db->select('a.id', true);
        $this->db->from($this->table_user_temp_name . ' AS a');
        $this->db->where('a.id', $temp_id);
        $this->db->where('a.opt_case', CASE_FORGET_PASSWORD);
        $this->db->where('a.deleted_at', null);
        $result = $this->db->count_all_results();
        if($result>0){
            //update main user
            $date = get_current_date();
            $data = array('password'=>$new_password, 'updated_at'=>$date);
            $this->db->trans_begin();
            $this->db->where('id', $id);
            $this->db->where('active_flg', 1);
            $this->db->where('deleted_at', null);
            $this->db->update($this->table_user_name, $data);
            if ($this->db->affected_rows() > 0) {
                //reupdate for temp
                $this->db->where('id', $temp_id);
                $this->db->update($this->table_user_temp_name, array('deleted_at'=>$date));
                if ($this->db->trans_status() === true && $this->db->affected_rows() > 0) {
                    $this->db->trans_commit();
                    return true;
                }
            } else {
                $this->db->trans_rollback();
                return false;
            }
        }
        return false;
    }
    ////////////////////////////////// END FORGET PASSWORD //////////////////////////////////////

    public function update($user_id, $info) {
        $this->db->trans_begin();
        $this->db->where('id', $user_id);
        $this->db->update($this->table_user_name, $info);
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }

    public function getAllUser($aSelect = array(), $aWhere = array(), $isMod=false, $limit=USER_LIMIT, $offset=0) {
        $result = null;
        if (count($aSelect) == 0) {
            $aSelect = array(
                'a.id',
                'username',
                'role',
                'password',
                'email',
                'phone',
                'address',
                'full_name',
                'image_folder',
                'image',
                'gender',
                'birthday',
                'active_flg',
                'deleted_at');
        }
        if (count($aWhere) == 0) {
            $aWhere = array('a.active_flg' => 1, 'a.deleted_at' => null);
        }
        $this->db->select(implode(',', $aSelect), true);
        $this->db->from($this->table_user_name . ' AS a');
        if($isMod){
            $aWhere['a.role <>'] = ROLE_ADMIN;
        }
        $this->db->where($aWhere);
        $this->db->limit($limit, $offset);
        $this->db->order_by('a.role');
        $this->db->order_by('a.id');
        $result = $this->db->get()->result('User_Entity');
        return $result;
    }

    /**
     * @todo admin direct insert new user
     * @param $data object
     * @return boolean
     *
    */
    public function insert($data){
        $this->db->select('a.id', true);
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->where('a.username', $data['username']);
        $this->db->or_where('a.email', $data['email']);
        $result = $this->db->count_all_results();
        if ($result > 0) {
            return false;
        }
        $this->db->select('a.id', true);
        $this->db->from($this->table_user_temp_name . ' AS a');
        $this->db->where('a.username', $data['username']);
        $this->db->or_where('a.email', $data['email']);
        $result = $this->db->count_all_results();
        if ($result > 0) {
            return false;
        }

        //send mail
        $aInfo = array(
            'subject' => SITE_NAME . ' - Đăng kí tài khoản',
            'template' => 'mail-template/admin-create.html.php',
            'data' => array(
                'username' => $data['username'],
                'password' => $data['password']
                ),
            'email' => $data['email'],
            'address' => array()
            );

        $data['password'] = $this->encrypt->encode($data['password']);

        $this->db->trans_begin();
        $this->db->insert($this->table_user_name, $data);

        $this->load->library('event');
        $resultMailer = $this->event->sendMail($aInfo);
        if ($this->db->trans_status() === false || !$resultMailer) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
            return true;
        }
        return false;
    }

    public function adminResetPassword($data){
        //send mail
        $aInfo = array(
            'subject' => SITE_NAME .' - Thay đổi thông tin đăng nhập',
            'template' => 'mail-template/admin-reset-pass.html.php',
            'data' => array(
                'username'  => $data['username'],
                'password'  => $data['password'],
                'full_name' => $data['full_name']
                ),
            'email' => $data['email'],
            'address' => array()
            );
        $this->db->trans_begin();
        $this->db->where('id', $data['id']);
        $this->db->update($this->table_user_name, array(
            'password'   => $this->encrypt->encode($data['password']),
            'updated_at' => get_current_date())
        );
        $this->load->library('event');
        $resultMailer = $this->event->sendMail($aInfo);
        if ($this->db->trans_status() === false || !$resultMailer) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
            return true;
        }
        return false;
    }

    public function countUser($options=array()){
        $this->db->select('a.id');
        $this->db->from($this->table_user_name . ' AS a');
        if(isset($options['is_mod']) && $options['is_mod']==true){
            $aWhere['a.role <>'] = ROLE_ADMIN;
        }
        if(isset($options['a_where'])){
            $this->db->where($options['a_where']);
        }
        if(isset($options['search_key'])){
            $this->db->like('username',     $options['search_key']);
            $this->db->or_like('email',     $options['search_key']);
            $this->db->or_like('phone',     $options['search_key']);
            $this->db->or_like('address',   $options['search_key']);
            $this->db->or_like('full_name', $options['search_key']);
            $this->db->or_like('birthday',  $options['search_key']);
        }
        $result = $this->db->count_all_results();
        return $result;
    }

    public function search($search_key, $aSelect = array(), $aWhere = array(), $isMod=false, $limit=USER_LIMIT, $offset=0) {
        $result = null;
        if (count($aSelect) == 0) {
            $aSelect = array(
                'a.id',
                'username',
                'role',
                'password',
                'email',
                'phone',
                'address',
                'full_name',
                'image_folder',
                'image',
                'gender',
                'birthday',
                'active_flg',
                'deleted_at');
        }
        if (count($aWhere) == 0) {
            $aWhere = array('a.active_flg' => 1, 'a.deleted_at' => null);
        }
        $this->db->select(implode(',', $aSelect), true);
        $this->db->from($this->table_user_name . ' AS a');
        if($isMod){
            $aWhere['a.role <>'] = ROLE_ADMIN;
        }
        $this->db->where($aWhere);
        $this->db->like('username', $search_key);
        $this->db->or_like('email', $search_key);
        $this->db->or_like('phone', $search_key);
        $this->db->or_like('address', $search_key);
        $this->db->or_like('full_name', $search_key);
        $this->db->or_like('birthday', $search_key);
        $this->db->limit($limit, $offset);
        $this->db->order_by('a.role');
        $this->db->order_by('a.id');
        $result = $this->db->get()->result('User_Entity');
        return $result;
    }
}
?>